package com.cug.nageoffer.service.impl;

import com.cug.nageoffer.mapper.ChatUserMapper;
import com.cug.nageoffer.model.entity.ChatUser;
import com.cug.nageoffer.model.vo.ChatUserVo;
import com.cug.nageoffer.model.vo.UserMsgVo;
import com.cug.nageoffer.model.vo.UserVo;
import com.cug.nageoffer.service.ChatUserService;
import com.cug.nageoffer.util.AuthContextUtil;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ChatUserServiceImpl implements ChatUserService {

    @Autowired
    private ChatUserMapper chatUserMapper;


    @Override
    public void init(HttpSession session) {
        // 从threadLocal获取聊天用户信息
        UserVo user = AuthContextUtil.get();
        log.info("聊天用户：{}初始化完成",user);
        // 将用户信息存储到session中
        session.setAttribute("username",user.getUsername());
        log.info("session存储信息：{}",session);
    }

    @Override
    public List<UserMsgVo> getHistoryByUsername(String username, String senderUsername) {
        List<UserMsgVo> list = chatUserMapper.selectByUsername(username, senderUsername);
        log.info("查询到历史记录：{}",list);
        return list;
    }


    @Override
    public void saveHistoryMsg(UserMsgVo userMsgVo) {
        log.info("存入聊天记录：{}",userMsgVo);
        chatUserMapper.insert(userMsgVo);
    }

    @Override
    public List<ChatUserVo> getChatListByUsername(String username) {
        // 获取所有聊天列表（sender = username || receiver = username）
        List<ChatUser> chatUsers = chatUserMapper.selectChatListByUsername(username);
        Set<ChatUserVo> chatUserVoList = new HashSet<>();
        // 过滤
        for (ChatUser chatUser : chatUsers) {
            ChatUserVo chatUserVo = new ChatUserVo();
            if(Objects.equals(chatUser.getSenderName(), username)){
                chatUserVo.setUsername(chatUser.getReceiverName());
                chatUserVo.setHeadImage(chatUser.getReceiverHeadImage());
                chatUserVoList.add(chatUserVo);
            }else {
                chatUserVo.setUsername(chatUser.getSenderName());
                chatUserVo.setHeadImage(chatUser.getSenderHeadImage());
                chatUserVoList.add(chatUserVo);
            }

        }

        return chatUserVoList.stream().toList();
    }

    /**
     * 保存聊天列表
     * @param chatUser
     */
    @Override
    public void saveChatList(ChatUser chatUser) {
        // 检查列表是否已保存数据
        String sendername = chatUserMapper.selectIsHave(chatUser);
        if(sendername != null){
            log.info("该聊天列表已存在");
            return;
        }
        chatUserMapper.insertChatList(chatUser);
    }
}
